import axios from "axios";
import { put, takeEvery } from "redux-saga/effects";
import { API } from "../../config";
import { FilterProductAction, filterProductSuccess, FILTER_PRODUCT, GetProductAction, GetProductByIdAciton, getProductByIdSuccess, getProductSuccess, GET_PRODUCT, GET_PRODUCT_BY_ID, SearchProductAction, searchProductSuccess, SEARCH_PRODUCT } from "../actions/product.action";
import { Product } from "../models/product";

function* handleGetProduct({sortBy,order,limit}: GetProductAction):any{
  let response = yield axios.get<Product[]>(`${API}/products`,{
    params: {
      sortBy,order,limit
    }
  })
  yield put(getProductSuccess(response.data,sortBy))
}

function* handleSearchProduct({ payload: { search, category } }:SearchProductAction):any{
  let response = yield axios.get(`${API}/products/search`,{
    params: {
      search,
      category
    }
  })
  yield put(searchProductSuccess(response.data))
}

function* handleFilterProduct({ payload }: FilterProductAction):any{
  let response = yield axios.post(`${API}/products/filter`, payload)
  yield put(filterProductSuccess(response.data, payload.skip))
}

function* handleProductById(action: GetProductByIdAciton):any{
  let resopnse = yield axios.get(`${API}/product/${action.payload.productId}`)
  yield put(getProductByIdSuccess(resopnse.data))
}

export default function* productSaga(){
  yield takeEvery(GET_PRODUCT,handleGetProduct)
  yield takeEvery(SEARCH_PRODUCT,handleSearchProduct)
  yield takeEvery(FILTER_PRODUCT,handleFilterProduct)
  yield takeEvery(GET_PRODUCT_BY_ID,handleProductById)
}